using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using AxCOMPLUSLib;
using System.Diagnostics;
using Newtonsoft;

namespace GXJD.QQ.Door
{
    class Program
    {
        /// <summary>
        /// 串口控件
        /// </summary>
        static private AxComPlus _com { get; set; }
        static private string comPort = "COM4";

        [STAThread]
        static void Main()
        {
            Console.Clear();
            Console.Title = "门禁开门服务";
            _com = new AxComPlus();

            //this.Controls.Add(_com);
            _com.CreateControl();

            using (HttpListener listerner = new HttpListener())
            {
                try
                {
                    listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问

                    listerner.Prefixes.Add("http://+:8080/door/");//允许监听本机所有IP连接方式
                    listerner.Start();
                    Console.WriteLine("Web启动成功，正在监听8080端口.......");
                    Debugger.Log(0, "WEB服务", "Web启动成功，正在监听8080端口.......");

                    while (true)
                    {
                        //等待请求连接
                        //没有请求则GetContext处于阻塞状态
                        HttpListenerContext ctx = listerner.GetContext();

                        //返回的model
                        var _resultmodel = new ResultModel()
                        {
                            isok = true,
                            message = string.Empty
                        };

                        //返回json类型
                        ctx.Response.ContentType = "application/json";
                        //返回json的字符编码
                        ctx.Response.ContentEncoding = Encoding.UTF8;
                        //设置返回给客服端http状态代码
                        ctx.Response.StatusCode = 200;


                        //获取GET传递的参数data
                        var json_data = string.Empty;
                        if (!string.IsNullOrEmpty(ctx.Request.QueryString["data"]))
                        {
                            try
                            {
                                //*
                                var str_data = ctx.Request.QueryString["data"];
                                Debugger.Log(0, "WEB服务", "传递参数data：" + str_data);

                                //Base64解码
                                json_data = UnBase64String(str_data);
                                Debugger.Log(0, "WEB服务", "传递参数：" + json_data);
                                //*/

                                /*
                                json_data = ctx.Request.QueryString["data"];
                                Debugger.Log(0, "WEB服务", "传递参数：" + json_data);
                                //*/

                                var _command = Newtonsoft.Json.JsonConvert.DeserializeObject<CommandModel>(json_data);
                                if (_command != null)
                                {
                                    Debugger.Log(0, "WEB服务", "传递参数：" + _command.UserName);
                                    //调用COM接口，发送开门指令
                                    OpenTheDoor(
                                        _command.UserName,
                                        _command.ComPort,
                                        _command.Address,
                                        _command.ReaderNumber);

                                }
                            }
                            catch (Exception ex)
                            {
                                Debugger.Log(0, "WEB服务", "运行错误：" + ex.Message);
                                _resultmodel.isok = false;
                                _resultmodel.message = ex.Message;
                            }
                        }
                        else
                        {
                            _resultmodel.isok = false;
                            _resultmodel.message = "GET的参数data未找到。";
                            Debugger.Log(0, "WEB服务", _resultmodel.message);
                        }

                        //使用Writer输出http响应代码
                        using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))
                        {
                            writer.Write(Newtonsoft.Json.JsonConvert.SerializeObject(_resultmodel));

                            writer.Close();
                            ctx.Response.Close();
                        }

                    }
                }
                finally
                {
                    Debugger.Log(0, "WEB服务", "Web服务停止.......");
                    listerner.Stop();
                    _com.StopAllCom();
                }
            }
        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="value">Base64字符串</param>
        /// <returns></returns>
        public static string UnBase64String(string value)
        {
            if (value == null || value == "")
            {
                return "";
            }
            byte[] bytes = Convert.FromBase64String(value);
            return Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// 编码
        /// </summary>
        /// <param name="value">普通字符串</param>
        /// <returns></returns>
        public static string ToBase64String(string value)
        {
            if (value == null || value == "")
            {
                return "";
            }
            byte[] bytes = Encoding.UTF8.GetBytes(value);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 遥控开门
        /// </summary>
        /// <param name="user">开门用户</param>
        /// <param name="port">端口号</param>
        /// <param name="addr">设备地址（控制器地址）</param>
        /// <param name="num">读卡器编号（门号）</param>
        public static void OpenTheDoor(
            string user,
            string port,
            short addr,
            string num)
        {
            if (_com.AddCom(port))
            {
                var i = _com.SendData(port, "0E", "000000", num, addr);
                Debugger.Log(0, "串口", "发送命令(串口：" + port + "；地址：" + addr + "；读卡器编号：" + num.ToString() + ")返回码：" + i.ToString());
            }
            else
            {
                Debugger.Log(0, "串口", "打开串口（" + port + "）错误！");
            }
        }

    }

}
